<?php

class admin_core_Settings_Form_Password extends Engine_Core_Form
{
	/**
	 * @var admin_core_Users
	 */
	protected $_adapter;

	/**
	 * @return admin_core_Users
	 */
	protected function getAdapter()
	{
		if (empty($this->_adapter)) {
			$this->_adapter = admin_core_Users::getInstance();
		}

		return $this->_adapter;
	}

    public function init()
    {
	    parent::init();
             
        $this->addElement('password', 'oldPassword', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('StringLength', false, array(0, 50)),
            ),
            'required'   => true,
            'label'      => 'Old password:',
        ));

        $this->addElement('password', 'newPassword', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('StringLength', false, array(0, 50)),
            ),
            'required'   => true,
            'label'      => 'New password:',
        ));

        $this->addElement('password', 'newPasswordAgain', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('StringLength', false, array(0, 50)),
            ),
            'required'   => true,
            'label'      => 'New password again:',
        ));

        $this->addElement('submit', 'send', array(
            'required' => false,
            'ignore'   => true,
            'label'    => 'Save',
        ));
    }

    public function isValid($data)
    {
        $valid = parent::isValid($data);

        if (!empty($data['oldPassword']) && !admin_core_Users::getInstance()->passwordValid($data['oldPassword'])) {
			$this->getElement('oldPassword')->addError('Password invalid');

			$valid = false;
        }

        if ($data['newPassword'] != $data['newPasswordAgain']) {
			$this->getElement('newPasswordAgain')->addError('Passwords are not equal');

			$valid = false;
        }

        $this->_errorsExist = !$valid;

        return $valid;
    }

	public function save()
	{
		$this->getAdapter()->saveEntry(array(
			'password' => $this->getValue('newPassword'),
			'id' => admin_core_Auth::getInstance()->getId()
		));
	}
}

